﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.LIB;
using YArchitech.Plumbing;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class LayEquipmentCoil : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Transaction transaction2 = null;
			Transaction transaction3 = null;
			ElementId elementId = null;
			ListItemPlane listItemPlane = null;
			Document document = null;
			RectLayParamers rectLayParamers = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException();
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				ElementSet elementSet = null;
				if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
				{
					(ViewType)1,
					(ViewType)2
				}))
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					HYEquipmentCommon hyequipmentCommon = new HYEquipmentCommon();
					ICollection<ElementId> allFamilyInstance = hyequipmentCommon.GetAllFamilyInstance(document, BuiltInCategory.OST_MechanicalEquipment);
					ICollection<Element> collectionId = null;
					LayToSelectionParameter layParameter = null;
					ILayForm layForm = new ILayForm(document);
					FamilySymbol familySymbol = layForm.LayDuctEquipmentCoilFormShow(document, "EquipmentCoil", layParameter);
					EquipmentCoilParam equipmentCoilPara = layForm.equipmentCoilPara;
					EquipmentCoilSetDetailParas equipmentCoilSetDetailParas = layForm.equipmentCoilSetDetailParas;
					LayAreaParameter layAreaParas = layForm.layAreaParas;
					rectLayParamers = layForm.rectLayParas;
					int layTerminalType = layForm.layTerminalType;
					listItemPlane = layForm.planeParam;
					bool flag = false;
					EquipmentCoilParameter eCoilParam = layForm.eCoilParam;
					bool hongYe = layForm.hongYe;
					if (familySymbol == null)
					{
						result = Autodesk.Revit.UI.Result.Cancelled;
					}
					else
					{
						if (familySymbol != null)
						{
							bool flag2 = true;
							ConnectHelper connectHelper = new ConnectHelper();
							if (listItemPlane != null)
							{
								if (4 == listItemPlane.PlaneType)
								{
									flag2 = true;
								}
								else
								{
									transaction2 = new Transaction(document, "创建平面");
									transaction2.Start();
									flag2 = false;
									if (2 == listItemPlane.PlaneType)
									{
										elementId = new ElementId(listItemPlane.PlaneId);
									}
									else
									{
										ReferencePlane referencePlane = document.Create.NewReferencePlane2(new XYZ(0.0, 0.0, listItemPlane.OffSet), new XYZ(0.0, 1.0, listItemPlane.OffSet), new XYZ(1.0, 0.0, listItemPlane.OffSet), document.ActiveView);
										if (referencePlane != null)
										{
											elementId = referencePlane.Id;
											if (YJKRevitTools.CheckReferencePlaneName(document, listItemPlane.PlaneName))
											{
												string text = Guid.NewGuid().ToString();
												referencePlane.Name = text;
												listItemPlane.PlaneName = text;
											}
											else
											{
												referencePlane.Name = listItemPlane.PlaneName;
											}
										}
										document.Regenerate();
									}
									transaction2.Commit();
								}
							}
							if (layTerminalType == 0 && flag2)
							{
								flag = true;
								try
								{
									activeUIDocument.PromptForFamilyInstancePlacement(familySymbol);
									goto IL_4E5;
								}
								catch (Exception)
								{
									goto IL_4E5;
								}
							}
							transaction = new Transaction(document, "风机盘管布置");
							transaction.Start();
							for (;;)
							{
								SubTransaction subTransaction = null;
								try
								{
									try
									{
										subTransaction = new SubTransaction(document);
										subTransaction.Start();
										if (!flag2 && layTerminalType == 0)
										{
											XYZ xyz = selection.PickPoint("选择一个点");
											Reference reference = UnifiedModified.GetReference(document.GetElementById(elementId) as ReferencePlane);
											elementSet = connectHelper.LayFamilyInstance(xyz, reference, familySymbol, document);
										}
										else if (layTerminalType == 3)
										{
											if (rectLayParamers == null)
											{
												MessageBox.Show("布置失败，区域布置参数为空", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
												break;
											}
											using (LayDuctTerminalRectDrawJin layDuctTerminalRectDrawJin = new LayDuctTerminalRectDrawJin(activeUIDocument, rectLayParamers))
											{
												rectLayParamers.PointBase = selection.PickPoint("选择第一个点，此点为矩形的基点：");
												layDuctTerminalRectDrawJin.StartPoint = rectLayParamers.PointBase;
												rectLayParamers.PointDiagonal = selection.PickPoint("选择第二个点，此点位矩形的对角点：");
												layDuctTerminalRectDrawJin.Dispose();
											}
											List<List<XYZ>> pointSet = new RectLayPoint(rectLayParamers).PointSet;
											if (pointSet != null && pointSet.Count > 0)
											{
												elementSet = new ElementSet();
												foreach (List<XYZ> xyzList in pointSet)
												{
													ElementSet elementSet2;
													if (!flag2)
													{
														Reference reference = UnifiedModified.GetReference(document.GetElementById(elementId) as ReferencePlane);
														elementSet2 = connectHelper.LayFamilyInstance(xyzList, reference, familySymbol, document);
													}
													else
													{
														elementSet2 = connectHelper.LayFamilyInstance(xyzList, familySymbol, document.ActiveView.GenLevel, 0, document);
													}
													foreach (object obj in elementSet2)
													{
														Element element = (Element)obj;
														elementSet.Insert(element);
													}
													document.Regenerate();
												}
												YJKRotateFamilyInstance hyrotateFamilyInstance = new YJKRotateFamilyInstance();
												IEnumerator enumerator2 = elementSet.GetEnumerator();
												{
													while (enumerator2.MoveNext())
													{
														object obj2 = enumerator2.Current;
														hyrotateFamilyInstance.RotateElem(document, obj2 as FamilyInstance, rectLayParamers.AngleRow);
													}
													goto IL_47E;
												}
											}
											MessageBox.Show("选取的区域太小，布置失败！", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
										}
										IL_47E:
										document.Regenerate();
										collectionId = hyequipmentCommon.GetAllTag(document, BuiltInCategory.OST_MechanicalEquipmentTags);
										if (elementSet != null)
										{
											this.SettingParameter(document, elementSet, collectionId, equipmentCoilPara, equipmentCoilSetDetailParas, flag2, 1, layForm.IsDBFamily, hongYe, eCoilParam);
										}
										subTransaction.Commit();
									}
									catch (Exception ex)
									{
										throw ex;
									}
									continue;
								}
								finally
								{
									if (subTransaction != null && (int)subTransaction.GetStatus() != 3)
									{
										subTransaction.RollBack();
									}
								}
								break;
							}
							transaction.Commit();
						}
						IL_4E5:
						if (flag)
						{
							bool isSetLevel = false;
							if (listItemPlane == null)
							{
								isSetLevel = true;
							}
							transaction3 = new Transaction(document, "设置风机盘管的参数");
							transaction3.Start();
							collectionId = hyequipmentCommon.GetAllTag(document, BuiltInCategory.OST_MechanicalEquipmentTags);
							IEnumerable<ElementId> allFamilyInstance2 = hyequipmentCommon.GetAllFamilyInstance(document, BuiltInCategory.OST_MechanicalEquipment);
							elementSet = new ElementSet();
							foreach (ElementId elementId2 in allFamilyInstance2)
							{
								bool flag3 = false;
								foreach (ElementId elementId3 in allFamilyInstance)
								{
									if (elementId2 == elementId3)
									{
										flag3 = true;
										break;
									}
								}
								if (!flag3)
								{
									elementSet.Insert(document.GetElementById(elementId2));
								}
							}
							this.SettingParameter(document, elementSet, collectionId, equipmentCoilPara, equipmentCoilSetDetailParas, isSetLevel, 2, layForm.IsDBFamily, hongYe, eCoilParam);
							transaction3.Commit();
						}
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex2)
			{
				message = ex2.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
                if (transaction != null && (int)transaction.GetStatus() == 1)
				{
					transaction.Commit();
				}
                if (transaction3 != null && (int)transaction3.GetStatus() != 3 && (int)transaction3.GetStatus() != 2)
				{
					transaction3.RollBack();
				}
                if (transaction2 != null && (int)transaction2.GetStatus() != 3)
				{
					transaction2.RollBack();
				}
				if (null != elementId && listItemPlane != null && document != null && (1 == listItemPlane.PlaneType || listItemPlane.PlaneType == 0))
				{
					Transaction transaction4 = new Transaction(document, "删除临时平面");
					transaction4.Start();
					document.Delete(elementId);
					transaction4.Commit();
				}
			}
			return result;
		}

		private void SettingParameter(Autodesk.Revit.DB.Document doc, ElementSet es, ICollection<Element> collectionId2, EquipmentCoilParam equipmentCoilPara, EquipmentCoilSetDetailParas equipmentCoilSetDetailParas, bool isSetLevel, int uni, bool isDbFamily, bool hongYe, EquipmentCoilParameter ecp)
		{
			Element element = null;
			Element element2 = null;
			bool flag = true;
			foreach (object obj in es)
			{
				Element element3 = (Element)obj;
				if (element3 != null)
				{
					XYZ point = (element3.Location as LocationPoint).Point;
					element = element3;
					bool flag2 = false;
					foreach (Element element4 in collectionId2)
					{
						if (((IndependentTag)element4).TaggedLocalElementId.IntegerValue == element3.Id.IntegerValue)
						{
							flag2 = true;
							element2 = element4;
							collectionId2.Remove(element4);
							break;
						}
					}
					if (!flag2 && equipmentCoilPara.Tag && flag)
					{
						try
						{
							doc.Create.NewTag(doc.ActiveView, element, false, 0, 0, point);
							goto IL_F7;
						}
						catch (Exception)
						{
							flag = false;
							MessageBox.Show("标注失败，可能原因是项目里没有标记族，请手动加载并配置", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
							goto IL_F7;
						}
						goto IL_DD;
					}
					goto IL_DD;
					IL_F7:
					if (!isDbFamily)
					{
						try
						{
							if (hongYe)
							{
								Parameter parameter = element3.GetParameter("统计名称");
								if (parameter != null && !parameter.IsReadOnly && equipmentCoilSetDetailParas.Name != "")
								{
									parameter.Set(equipmentCoilSetDetailParas.Name);
								}
								Parameter parameter2 = element3.GetParameter("长度");
								if (parameter2 != null && !parameter2.IsReadOnly && equipmentCoilSetDetailParas.Length != 0.0)
								{
									parameter2.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Length, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter3 = element3.GetParameter("宽度");
								if (parameter3 != null && !parameter3.IsReadOnly && equipmentCoilSetDetailParas.Width != 0.0)
								{
									parameter3.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Width, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter4 = element3.GetParameter("高度");
								if (parameter4 != null && !parameter4.IsReadOnly && equipmentCoilSetDetailParas.High != 0.0)
								{
									parameter4.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.High, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter5 = element3.GetParameter("厚度");
								if (parameter5 != null && !parameter5.IsReadOnly && equipmentCoilSetDetailParas.High != 0.0)
								{
									parameter5.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.High, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter6 = element3.GetParameter("制冷量");
								if (parameter6 != null && !parameter6.IsReadOnly)
								{
									parameter6.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.CoolPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								Parameter parameter7 = element3.GetParameter("制热量");
								if (parameter7 != null && !parameter7.IsReadOnly)
								{
									parameter7.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.HotPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								Parameter parameter8 = element3.GetParameter("风量");
								if (parameter8 != null && !parameter8.IsReadOnly)
								{
									parameter8.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Wind, (Autodesk.Revit.DB.DisplayUnitType)66));
								}
								Parameter parameter9 = element3.GetParameter("水流量");
								if (parameter9 != null && !parameter9.IsReadOnly)
								{
									parameter9.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Water / 1000.0, (Autodesk.Revit.DB.DisplayUnitType)66));
								}
								Parameter parameter10 = element3.GetParameter("进水口接管管径");
								if (parameter10 != null && !parameter10.IsReadOnly && equipmentCoilSetDetailParas.PipeInDim != 0.0)
								{
									parameter10.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.PipeInDim, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter11 = element3.GetParameter("出水口接管管径");
								if (parameter11 != null && !parameter11.IsReadOnly && equipmentCoilSetDetailParas.PipeOutDim != 0.0)
								{
									parameter11.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.PipeOutDim, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter12 = element3.GetParameter("冷凝水接管管径");
								if (parameter12 != null && !parameter12.IsReadOnly && equipmentCoilSetDetailParas.PipeCoolDim != 0.0)
								{
									parameter12.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.PipeCoolDim, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter13 = element3.GetParameter("送风口宽度");
								if (parameter13 != null && !parameter13.IsReadOnly && equipmentCoilSetDetailParas.DuctSupplyWidth != 0.0)
								{
									parameter13.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.DuctSupplyWidth, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter14 = element3.GetParameter("送风口高度");
								if (parameter14 != null && !parameter14.IsReadOnly && equipmentCoilSetDetailParas.DuctSupplyHigh != 0.0)
								{
									parameter14.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.DuctSupplyHigh, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter15 = element3.GetParameter("回风口宽度");
								if (parameter15 != null && !parameter15.IsReadOnly && equipmentCoilSetDetailParas.Length / 2.0 != 0.0)
								{
									parameter15.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Length / 2.0, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter16 = element3.GetParameter("回风口高度");
								if (parameter16 != null && !parameter16.IsReadOnly && equipmentCoilSetDetailParas.Width / 2.0 != 0.0)
								{
									parameter16.Set(UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Width / 2.0, (Autodesk.Revit.DB.DisplayUnitType)2));
								}
								Parameter parameter17 = element3.GetParameters("风机盘管厂家").FirstOrDefault<Parameter>();
								if (parameter17 != null && !parameter17.IsReadOnly)
								{
									parameter17.Set(ecp.Factory);
								}
								Parameter parameter18 = element3.GetParameters("风机盘管结构形式").FirstOrDefault<Parameter>();
								if (parameter18 != null && !parameter18.IsReadOnly)
								{
									parameter18.Set(ecp.StructType);
								}
								Parameter parameter19 = element3.GetParameters("风机盘管安装形式").FirstOrDefault<Parameter>();
								if (parameter19 != null && !parameter19.IsReadOnly)
								{
									parameter19.Set(ecp.InstallType);
								}
								Parameter parameter20 = element3.GetParameters("风机盘管型号").FirstOrDefault<Parameter>();
								if (parameter20 != null && !parameter20.IsReadOnly)
								{
									parameter20.Set(ecp.Name);
								}
							}
							else
							{
								FamilyInstance familyInstance = element3 as FamilyInstance;
								if (equipmentCoilSetDetailParas.CoolPower != 0.0)
								{
									this.SetParameterValue(familyInstance.Symbol, "制冷量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.CoolPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								if (equipmentCoilSetDetailParas.HotPower != 0.0)
								{
									this.SetParameterValue(familyInstance.Symbol, "制热量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.HotPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								if (equipmentCoilSetDetailParas.Wind != 0.0)
								{
									this.SetParameterValue(familyInstance.Symbol, "风量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Wind, (Autodesk.Revit.DB.DisplayUnitType)66));
								}
								if (equipmentCoilSetDetailParas.CoolPower != 0.0)
								{
									this.SetParameterValue(familyInstance, "制冷量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.CoolPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								if (equipmentCoilSetDetailParas.HotPower != 0.0)
								{
									this.SetParameterValue(familyInstance, "制热量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.HotPower, (Autodesk.Revit.DB.DisplayUnitType)39));
								}
								if (equipmentCoilSetDetailParas.Wind != 0.0)
								{
									this.SetParameterValue(familyInstance, "风量", UnitConvert.CovertToAPI(equipmentCoilSetDetailParas.Wind, (Autodesk.Revit.DB.DisplayUnitType)66));
								}
							}
						}
						catch (Exception ex)
						{
							MessageBox.Show(ex.Message, "盈建科提示");
						}
					}
					if (isSetLevel)
					{
						Parameter parameter21 = null;
						Parameter parameter22 = null;
						double num = 0.0;
						if (element.GetParameter(BuiltInParameter.INSTANCE_ELEVATION_PARAM) != null)
						{
							parameter22 = element.GetParameter(BuiltInParameter.INSTANCE_ELEVATION_PARAM);
						}
						else
						{
							Parameter parameter23 = element.GetParameter(BuiltInParameter.FAMILY_LEVEL_PARAM);
							if (parameter23 != null)
							{
								parameter23.Set(doc.ActiveView.GenLevel.Id);
							}
						}
						if (parameter22 != null)
						{
							parameter22.Set(UnitConvert.CovertToAPI(equipmentCoilPara.OffSet * 1000.0, (Autodesk.Revit.DB.DisplayUnitType)2));
							num = parameter22.AsDouble();
						}
						if (num != UnitConvert.CovertToAPI(equipmentCoilPara.OffSet * 1000.0, (Autodesk.Revit.DB.DisplayUnitType)2))
						{
							if (element.GetParameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM) != null)
							{
								parameter21 = element.GetParameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
							}
							if (parameter21 != null)
							{
								parameter21.Set(UnitConvert.CovertToAPI(equipmentCoilPara.OffSet * 1000.0, (Autodesk.Revit.DB.DisplayUnitType)2));
							}
						}
					}
					else if (uni == 1)
					{
						Parameter parameter24 = null;
						if (element.GetParameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM) != null)
						{
							parameter24 = element.GetParameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
						}
						if (parameter24 != null)
						{
							parameter24.Set(0);
						}
					}
					doc.Regenerate();
					continue;
					IL_DD:
					if (flag2 && !equipmentCoilPara.Tag)
					{
						doc.Delete(element2.Id);
						goto IL_F7;
					}
					goto IL_F7;
				}
			}
		}

		private void SetParameterValue(Element elem, string paramName, double paramValue)
		{
			Parameter parameter = elem.GetParameter(paramName);
			if (parameter != null && !parameter.IsReadOnly)
			{
				parameter.Set(paramValue);
			}
		}

		private double GetCoolingDesign(IList<Element> elems)
		{
			double num = 0.0;
			foreach (Element element in elems)
			{
				if (element != null && element is Space)
				{
					Parameter parameter = element.GetParameter(BuiltInParameter.ROOM_DESIGN_COOLING_LOAD_PARAM);
					if (parameter != null)
					{
                        num += UnitConvert.CovertFromAPI((DisplayUnitType)40, parameter.AsDouble());
					}
				}
			}
			return num;
		}
	}
}
